import random
import time

from flask import render_template, jsonify, Blueprint, request

from app.model.models import db, NodeData, LinkData

flowchart_routes = Blueprint('flowchart', __name__)

# 模拟节点状态
node_status = {}


@flowchart_routes.route('/<int:project_id>')
def index(project_id):
    return render_template('flowchart.html', project_id=project_id)


@flowchart_routes.route('/data/<int:project_id>')
def fetch_data(project_id):
    node_data = NodeData.query.filter_by(project_id=project_id).all()
    node_data_str = [p.to_dict() for p in node_data]
    link_data = LinkData.query.filter_by(project_id=project_id).all()
    link_data_str = [p.to_dict() for p in link_data]
    data = {"node_data": node_data_str, "link_data": link_data_str}
    return jsonify(data)


@flowchart_routes.route('/run_node/<int:node_id>', methods=['POST'])
def run_node(node_id):
    # 模拟大模型处理时间
    time.sleep(random.uniform(1, 3))

    # 随机生成状态
    status = random.choice(['running', 'success', 'failed'])
    node_status[node_id] = status

    return jsonify({
        'node_id': node_id,
        'status': status
    })


@flowchart_routes.route('/get_status/<int:node_id>')
def get_status(node_id):
    return jsonify({
        'node_id': node_id,
        'status': node_status.get(node_id, 'idle')
    })


# 节点增删改接口
@flowchart_routes.route('/nodes_links', methods=['POST'])
def create_node():
    data = request.get_json()
    project_id = data['project_id']
    link_data = data['link_data']
    node_data = data['node_data']
    if isinstance(node_data, list):  # 批量保存
        nodes = [NodeData(
            id=None,
            key=item['key'],
            category=item['category'],
            text=item['text'],
            loc=item['loc'],
            project_id=project_id
        ) for item in node_data]
        NodeData.query.filter_by(project_id=project_id).delete()
        db.session.bulk_save_objects(nodes)
    if isinstance(link_data, list):  # 批量保存
        links = [LinkData(
            id=None,
            from_=item['from'],
            to=item['to'],
            text=item['text'],
            project_id=project_id
        ) for item in link_data]
        LinkData.query.filter_by(project_id=project_id).delete()
        db.session.bulk_save_objects(links)
    db.session.commit()
    return jsonify({'message': 'Nodes created successfully'}), 201


@flowchart_routes.route('/nodes/batch', methods=['POST'])
def batch_create_nodes():
    data = request.get_json()
    nodes = [NodeData(
        key=item['key'],
        category=item['category'],
        text=item['text'],
        loc=item['loc']
    ) for item in data]
    db.session.bulk_save_objects(nodes)
    db.session.commit()
    return jsonify({'message': 'Nodes created successfully'}), 201


@flowchart_routes.route('/nodes/<string:node_id>', methods=['PUT'])
def update_node(node_id):
    node = NodeData.query.get_or_404(node_id)
    data = request.get_json()
    node.category = data.get('category', node.category)
    node.text = data.get('text', node.text)
    node.loc = data.get('loc', node.loc)
    db.session.commit()
    return jsonify({'message': 'Node updated successfully'})


@flowchart_routes.route('/nodes/<string:node_id>', methods=['DELETE'])
def delete_node(node_id):
    node = NodeData.query.get_or_404(node_id)
    db.session.delete(node)
    db.session.commit()
    return jsonify({'message': 'Node deleted successfully'})


# 连接线增删改接口
@flowchart_routes.route('/links', methods=['POST'])
def create_link():
    data = request.get_json()
    if isinstance(data, list):  # 批量保存
        links = [LinkData(
            id=None,
            from_=item['from'],
            to=item['to'],
            text=item['text']
        ) for item in data]
        db.session.bulk_save_objects(links)
    else:  # 单个保存
        link = LinkData(
            id=None,
            from_=data['from'],
            to=data['to'],
            text=data['text']
        )
        db.session.add(link)
    db.session.commit()
    return jsonify({'message': 'Links created successfully'}), 201


@flowchart_routes.route('/links/batch', methods=['POST'])
def batch_create_links():
    data = request.get_json()
    links = [LinkData(
        id=None,
        from_=item['from'],
        to=item['to'],
        text=item['text']
    ) for item in data]
    db.session.bulk_save_objects(links)
    db.session.commit()
    return jsonify({'message': 'Links created successfully'}), 201


@flowchart_routes.route('/links/<int:link_id>', methods=['PUT'])
def update_link(link_id):
    link = LinkData.query.get_or_404(link_id)
    data = request.get_json()
    link.from_ = data.get('from', link.from_)
    link.to = data.get('to', link.to)
    link.points = data.get('points', link.points)
    db.session.commit()
    return jsonify({'message': 'Link updated successfully'})


@flowchart_routes.route('/links/<int:link_id>', methods=['DELETE'])
def delete_link(link_id):
    link = LinkData.query.get_or_404(link_id)
    db.session.delete(link)
    db.session.commit()
    return jsonify({'message': 'Link deleted successfully'})
